var bsurl = require('../../../utils/baseUrl.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    noGoods:false,/**无数据加界面 */
    carts: [],
    startX: 0,
    itemLefts: [],
    buyCount:[],
    checkItem:[],
    minusStatuses:[],
    selectedAllStatus:0,
    total:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.editTabBar(app.globalData.tabBar1);
    var list = wx.getStorageSync('goodsList');
    console.log(list);
    if(!list[0]){
      this.setData({noGoods:true})
    } 
    this.setData({carts:list});
    this.init();
  },
  //选择按钮
  bindCheckbox: function (e) {
    console.log("check");
    var index = e.currentTarget.dataset.index;
    var n = 0;
    var price = this.data.carts[index].price * this.data.buyCount[index];
    if(this.data.checkItem[index]){
      n = -1;
      price = -price;
    }
    else{
      n = 1;
    }
    this.data.checkItem[index] = !this.data.checkItem[index];
    this.setData({
      checkItem:this.data.checkItem,
      selectedAllStatus: this.data.selectedAllStatus+n,
      total:this.formatPrice(this.data.total + price)
    });
  },
  //全选按钮
  bindSelectAll: function () {
    console.log("selectAll");
    var value = this.data.selectedAllStatus > 0?false:true
    var price = 0;
    for(var i in this.data.checkItem){
      this.data.checkItem[i] = value;
      price += this.data.carts[i].price * this.data.buyCount[i];
    }
    this.data.selectedAllStatus = this.data.selectedAllStatus > 0 ? 0 : this.data.checkItem.length;
    if (!this.data.selectedAllStatus){price = 0;}
    this.setData({
      checkItem: this.data.checkItem,
      selectedAllStatus: this.data.selectedAllStatus,
      total: this.formatPrice(price)
    });
    console.log(this.data.checkItem)
    console.log(this.data.selectedAllStatus);
  },
  //商品详情
  showGoods:function(e){
    console.log("showGoods");
    wx.setStorageSync('goods',this.data.carts[e.currentTarget.dataset.index]);
    wx.navigateTo({
      url: '../product/detail',
    })
  },
  //减少数量
  bindMinus:function(e){
    console.log("min");
    var index = e.currentTarget.dataset.index;
    this.data.minusStatuses[index] = this.data.buyCount[index]>1?"normal":"disabled";
    if (this.data.buyCount[index] > 1){
      this.data.buyCount[index]--;
    }else{return;}
    var price = 0;
    if (this.data.checkItem[index]) {
      price = -this.data.carts[index].price;
    }
    this.setData({
      minusStatuses: this.data.minusStatuses,
      buyCount: this.data.buyCount,
      total: this.formatPrice(this.data.total + price)
    })
  },
  //增加数量
  bindPlus:function(e){
    console.log("add");
    var index = e.currentTarget.dataset.index;
    this.data.buyCount[index]++;
    this.data.minusStatuses[index] = this.data.buyCount[index] > 1 ? "normal" : "disabled";
    var price = 0;
    if (this.data.checkItem[index]) {
      price = this.data.carts[index].price;
    }
    this.setData({
      minusStatuses: this.data.minusStatuses,
      buyCount: this.data.buyCount,
      total: this.formatPrice(this.data.total + price)
    })
  },
  //直接输入数量
  bindManual:function(e){
    console.log(e)
    var num = Number(e.detail.value) > 1 ? Number(e.detail.value):1;
    this.data.buyCount[e.currentTarget.dataset.index] = num;
    this.setData({ buyCount: this.data.buyCount });
  },
  bindManualTapped: function () {
    // 什么都不做，只为打断跳转
  },
  //删除按钮
  deleteGoods:function(e){
    console.log("del")
    var index = e.currentTarget.dataset.index;
    console.log(index);
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认要删除吗',
      success: function (res) {
        that.deleteFromCart(index);
      }
    });
  },
  //下单按钮
  bindOrder:function(){
    console.log(this.data.buyCount)
    console.log(this.data.checkItem)
    console.log(this.data.carts)
    if (!this.data.selectedAllStatus){
      return;
    }
    var addr = wx.getStorageSync('address');
    if(!addr){
      wx.navigateTo({
        url: '../address/address',
      });
      return;
    }
    var goodsList = []
    for(var i in this.data.carts){
      if(this.data.checkItem[Number(i)]){
        var goods_order = {};
        goods_order.goodsid = this.data.carts[i].goodsid;
        goods_order.goodssort = this.data.carts[i].goodssort;
        goods_order.goodsname = this.data.carts[i].goodsname;
        goods_order.price = this.data.carts[i].price;
        goods_order.username = this.data.carts[i].username;
        goods_order.num = this.data.buyCount[Number(i)];
        goodsList.push(goods_order);
      }
    }
    wx.showToast({
      title: '加载中...',
      icon: "loading",
      duration: 250000
    })
    var that = this;
    wx.request({
      url: bsurl + "buyer/addOrder.do",
      method: "post",
      data: {
        body: {
          address: addr.recname+" "+addr.phone+" "+addr.addr,
          goodsList: goodsList
        }
      },
      header: {
        'content-type': 'application/json', // 默认值
        JSESSIONID: app.globalData.JSESSIONID
      },
      success: function (res) {
        wx.hideToast();
        if (res.statusCode != 200) {
          wx.showModal({
            title: '提示',
            content: "请求失败",
          });
          return;
        }
        console.log(res);
        if (res.data.success) {
          var carts = [];
          var checkItem = [];
          var buyCount = [];
          var none = false;
          for (var i in that.data.carts) {
            if (!that.data.checkItem[Number(i)]) {
              carts.push(that.data.carts[i]);
              checkItem.push(that.data.checkItem[Number(i)]);
              buyCount.push(that.data.buyCount[Number(i)]);
            }else{none = true;}
          }
          that.setData({carts:carts,checkItem:checkItem,buyCount:buyCount,noGoods:none});
          wx.setStorageSync("goodsList", carts);

          wx.showToast({
            title: '下单成功',
            icon: "success"
          })
        }
        else {
          wx.showModal({
            title: '提示',
            content: res.data.message,
          });
        }
      },
      fail: function (res) {
        wx.hideToast();
        wx.showModal({
          title: '提示',
          content: "网络请求失败",
        });
      }
    })
  },
  touchStart: function (e) {
    var startX = e.touches[0].clientX;
    this.setData({
      startX: startX,
      itemLefts: []
    });
  },
  touchMove: function (e) {
    var index = e.currentTarget.dataset.index;
    var movedX = e.touches[0].clientX;
    var distance = this.data.startX - movedX;
    var itemLefts = this.data.itemLefts;
    itemLefts[index] = -distance;
    this.setData({
      itemLefts: itemLefts
    });
  },
  touchEnd: function (e) {
    var index = e.currentTarget.dataset.index;
    var endX = e.changedTouches[0].clientX;
    var distance = this.data.startX - endX;
    // button width is 60
    var buttonWidth = 60;
    if (distance <= 0) {
      distance = 0;
    } else {
      if (distance >= buttonWidth) {
        distance = buttonWidth;
      } else if (distance >= buttonWidth / 2) {
        distance = buttonWidth;
      } else {
        distance = 0;
      }
    }
    var itemLefts = this.data.itemLefts;
    itemLefts[index] = -distance;
    this.setData({
      itemLefts: itemLefts
    });
  },
  //删除,所有选择状态待做，暂重置状态
  deleteFromCart:function(index){ 
    this.data.carts.splice(index,1);
    this.init();
    this.setData({
      carts: this.data.carts
    })
    if (!this.data.carts.length){
      this.setData({noGoods:true});
    }
    console.log(this.data.carts);
    wx.setStorageSync('goodsList', this.data.carts);
  },
  //价格小数
  formatPrice:function(price){
    return Math.round(price*100)/100;
  },
  //初始化数据
  init:function(){
    var buyCount = [];
    var checkItem = [];
    for (var i in this.data.carts) {
      buyCount[i] = 1;
      checkItem[i] = false;
    }
    this.setData({
      buyCount: buyCount,
      checkItem: checkItem,
      total:0,
      selectedAllStatus:0
    })
  }
})